package com.hqd.ch03.v40.web.method.annotation;

import com.hqd.ch03.v40.core.MethodParameter;
import com.hqd.ch03.v40.web.bind.annotation.RequestAttribute;
import com.hqd.ch03.v40.web.bind.annotation.ValueConstants;
import com.hqd.ch03.v40.web.context.request.NativeWebRequest;
import com.hqd.ch03.v40.web.context.request.RequestAttributes;
import com.hqd.ch03.v40.web.servlet.mvc.method.annotation.AbstractNamedValueMethodArgumentResolver;

import javax.servlet.ServletException;

public class RequestAttributeMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestAttribute.class);
    }

    @Override
    protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
        RequestAttribute ann = parameter.getParameterAnnotation(RequestAttribute.class);
        return new NamedValueInfo(ann.name(), ann.required(), ValueConstants.DEFAULT_NONE);
    }

    @Override
    protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) {
        return request.getAttribute(name, RequestAttributes.SCOPE_REQUEST);
    }

    @Override
    protected void handleMissingValue(String name, MethodParameter parameter) throws ServletException {
    }

}
